package com.sky.controller.admin.common;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import com.sun.tools.sjavac.Log;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/admin/common")
public class UploadController {
	
	private final AliOssUtil aliOssUtil;
	
	public UploadController(AliOssUtil aliOssUtil) {this.aliOssUtil = aliOssUtil;}
	
	@PostMapping("/upload")
	public Result<String> uploadImage(MultipartFile file) {
		if (file == null) {
			return Result.error(MessageConstant.UPLOAD_FAILED);
		}
		try {
			String filename = file.getOriginalFilename();
			assert filename != null;
			String imageUrl = aliOssUtil.upload(file.getBytes(),
					UUID.randomUUID() + filename.substring(filename.lastIndexOf(".")));
			return Result.success(imageUrl);
		} catch (IOException | NullPointerException e) {
			Log.info(MessageConstant.UPLOAD_FAILED + ": " + e);
			return Result.error(MessageConstant.UPLOAD_FAILED);
		}
	}
}
